import datetime
import time
from tkinter import *
import re
import paramiko


def ConnectServer(ip, port, user, pwd):
    # 创建实例对象
    ssh = paramiko.SSHClient()
    # 调用方法，表示没有存储远程机器的公钥，允许访问
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(ip, port, user, pwd, timeout=10)
        print("服务器连接成功！\n")
        return ssh
    except Exception:
        print("server port not connect!")
        return 0


# cpu的使用率
def cpu_use(ssh):
    # print("cpu使用率：")
    stdin, stdout, stderr = ssh.exec_command('cat /proc/stat | grep "cpu "')
    str_out = stdout.read().decode()
    str_err = stderr.read().decode()
    if str_err != "":
        print(str_err)
    else:
        cpu_time_list = re.findall('\d+', str_out)
        cpu_idle1 = cpu_time_list[3]
        total_cpu_time1 = 0
        for t in cpu_time_list:
            total_cpu_time1 = total_cpu_time1 + int(t)
    time.sleep(2)
    stdin, stdout, stderr = ssh.exec_command('cat /proc/stat | grep "cpu "')
    str_out = stdout.read().decode()
    str_err = stderr.read().decode()
    if str_err != "":
        print(str_err)
    else:
        cpu_time_list = re.findall('\d+', str_out)
        cpu_idle2 = cpu_time_list[3]
        total_cpu_time2 = 0
        for t in cpu_time_list:
            total_cpu_time2 = total_cpu_time2 + int(t)
    cpu_usage = round(1 - (float(cpu_idle2) - float(cpu_idle1)) / (total_cpu_time2 - total_cpu_time1), 2)
    print('当前CPU使用率为：' + str(cpu_usage))
    print("\n")
    return cpu_usage


# 获取内存使用量
def get_mem_used(ssh):
    print("内存使用率：")
    command = r"cat /proc/meminfo"
    stdin, stdout, stderr = ssh.exec_command(command)
    outs = stdout.readlines()
    res = {'total': 0, 'free': 0, 'buffers': 0, 'cached': 0}
    index = 0
    for line in outs:
        if (index == 4):
            break
        line = line.lstrip()
        memItem = line.lower().split()
        if memItem[0] == 'memtotal:':
            res['total'] = int(memItem[1])
            index = index + 1
            continue
        elif memItem[0] == 'memfree:':
            res['memfree'] = int(memItem[1])
            index = index + 1
            continue
        elif memItem[0] == 'buffers:':
            res['buffers'] = int(memItem[1])
            index = index + 1
            continue
        elif memItem[0] == 'cached:':
            res['cached'] = int(memItem[1])
            index = index + 1
            continue
    spu_used = res['total'] - res['free'] - res['buffers'] - res['cached']
    result = spu_used / res['total']
    spu_used = '%.2f%%' % (result * 100)
    print(spu_used)
    print("\n")
    return spu_used


# 网络流量
def netstat(ssh):
    print("网络流量：")
    stdin, stdout, stderr = ssh.exec_command('cat /proc/net/dev')
    str_out = stdout.read().decode()
    str_err = stderr.read().decode()
    if str_err != "":
        print(str_err)
    print(str_out)
    return str_out


# 文件系统使用情况
def cipan(ssh):
    print("文件系统磁盘使用情况统计：")
    stdin, stdout, stderr = ssh.exec_command('df -lm')
    str_out = stdout.read().decode()
    str_err = stderr.read().decode()

    if str_err != "":
        print(str_err)

    print(str_out)
    return str_out


# 查看进程数量(获取进程绝对路径可以用pid来表示/proc/pid/exe   将pid更换即可
def get_process_info(client):
    command = 'ps aux'
    stdin, stdout, stderr = client.exec_command(command)
    index = 0
    process = []
    title = "user\tpid\tcpu\tmem\n"
    process.append(title)
    for i, line in enumerate(stdout):
        result = line.strip("\n")
        result = result.split('\t')[0]
        result1 = result.split(' ')
        for i in range(result1.count('')):
            result1.remove('')
        # print(result1)
        if index == 0:
            index += 1

            continue
        user = result1[0]
        pid = result1[1]
        cpu = float(result1[2])
        mem = float(result1[3])
        if cpu == 0.0 and mem == 0.0:
            continue
        print('user', user)
        print("pid", pid)
        print("cpu_used", cpu)
        print('mem', mem)
        processinfo = str(user) + "\t" + str(pid) + "\t" + str(cpu) + "\t" + str(mem) + "\n"
        process.append(processinfo)
        index += 1
    print("进程数量：" + str(index))
    return process


def New():
    Linux = Toplevel()
    Linux.geometry("400x400+200+200")
    Linux.title("查询")

    IP = StringVar()
    Port = StringVar()
    UserName = StringVar()
    Password = StringVar()

    show = []
    label_IP = Label(Linux, text="IP")
    show.append(label_IP)
    entry_IP = Entry(Linux, textvariable=IP)
    show.append(entry_IP)
    label_Port = Label(Linux, text="Port")
    show.append(label_Port)
    entry_Port = Entry(Linux, textvariable=Port)
    show.append(entry_Port)
    label_UserName = Label(Linux, text="UserName")
    show.append(label_UserName)
    entry_UserName = Entry(Linux, textvariable=UserName)
    show.append(entry_UserName)
    label_Password = Label(Linux, text="Password")
    show.append(label_Password)
    entry_Password = Entry(Linux, textvariable=Password)
    show.append(entry_Password)

    nowtime = StringVar()
    CPUUse = StringVar()
    SpuUse = StringVar()
    timeinfo = Label(Linux, textvariable=nowtime)
    text_netstat = Text(Linux, width=130, height=5)
    text_cipan = Text(Linux, width=80, height=100)
    text_process = Text(Linux, width=80, height=100)
    CPUinfo = Label(Linux, textvariable=CPUUse)
    spuusedinfo = Label(Linux, textvariable=SpuUse)

    timeinfo.pack()
    CPUinfo.pack()
    spuusedinfo.pack()
    text_netstat.pack()
    text_cipan.pack(side=LEFT)
    text_process.pack(side=RIGHT)

    def getinfo():
        target_IP = IP.get()
        target_Port = int(Port.get())
        target_User = UserName.get()
        target_Pwd = Password.get()
        print("IP: " + target_IP, "Port: " + str(target_Port), "UserName: " + target_User, "Pwd: " + target_Pwd)

        ssh = ConnectServer(target_IP, target_Port, target_User, target_Pwd)

        if ssh == 0:
            label_login = Label(Linux, text="Login Failed!")
            label_login.pack()
            print("服务器登录失败！")
            # messagebox.showerror(message="连接失败！")
        else:
            label_login = Label(Linux, text="Login Success!")
            label_login.pack()
            showinfo(ssh)
            print("服务器登录成功！")
            # messagebox.showinfo(message="连接成功！")

    def showinfo(ssh):
        # 获取当前时间
        now_time = datetime.datetime.now().strftime('%F %T')

        CPU = cpu_use(ssh)
        spu_used = get_mem_used(ssh)
        netstatss = netstat(ssh)
        cipanss = cipan(ssh)
        processss = get_process_info(ssh)

        CPUUse.set("CPU使用情况：" + str(CPU))
        nowtime.set(now_time)
        SpuUse.set("内存使用情况：" + str(spu_used))

        text_cipan.delete(0.0, END)
        text_netstat.delete(0.0, END)
        text_process.delete(0.0, END)

        text_cipan.insert(INSERT, cipanss)
        text_netstat.insert(INSERT, netstatss)
        for line in processss:
            text_process.insert(INSERT, line)

    def clearinfo():
        print("loginout!\n")
        IP.set("")
        Port.set("")
        UserName.set("")
        Password.set("")

    button_Check = Button(Linux, text="查询", command=getinfo)
    show.append(button_Check)
    button_Out = Button(Linux, text="退出", command=clearinfo)
    show.append(button_Out)
    for item in show:
        item.pack()
    Linux.mainloop()


top = Tk()
top.geometry("400x400+200+200")
top.title("主界面")
button = Button(top, text='新的监视对象', command=New)
button.pack()
top.mainloop()
